package io.jee.medusa.invoke.mail;

import java.io.UnsupportedEncodingException;

import javax.mail.internet.MimeUtility;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.util.StringUtils;

import io.jee.medusa.utils.ResultModel;

public class DefaultMailSenderService implements MailSenderService {
	
	protected final Log logger = LogFactory.getLog(getClass());
	private JavaMailSender javaMailSender;
	private String nickname;
	private String username;
	
	public DefaultMailSenderService(String host, String username, String password, String nickname) {
		this.username = username;
		try {
			this.nickname = MimeUtility.encodeText(nickname)+" <"+username+">";
		} catch (UnsupportedEncodingException e) {
			this.nickname = username;
		}
		JavaMailSenderImpl mail = new JavaMailSenderImpl();
		mail.setHost(host);
		mail.setUsername(username);
		mail.setPassword(password);
		javaMailSender = mail;
	}

	@Override
	public ResultModel<Void> send(String to, String subject, String text, String nickname) {
		SimpleMailMessage simpleMessage = new SimpleMailMessage();
		simpleMessage.setTo(to);
		if(StringUtils.hasText(nickname)){
			try {
				nickname = MimeUtility.encodeText(nickname)+" <"+this.username+">";
			} catch (UnsupportedEncodingException e) {
				nickname = username;
			}
			simpleMessage.setFrom(nickname);
		}else{
			simpleMessage.setFrom(this.nickname);
		}
		simpleMessage.setSubject(subject);
		simpleMessage.setText(text);
		try{
			javaMailSender.send(simpleMessage);
			return ResultModel.result(true, "邮件发送成功");
		}catch(Exception e){
			logger.warn("邮件发送失败："+e.getMessage());
			return ResultModel.result(false, e.getMessage());
		}
	}
	
	@Override
	public ResultModel<Void> send(String to, String subject, String text) {
		return send(to, subject, text, null);
	}

}
